package com.icloud.gateway.authorization;

import com.icloud.common.cache.util.TokenUtil;
import com.icloud.common.web.domain.UserDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

import java.util.concurrent.Future;

/**
 * 鉴权管理器，用于异步获取检测token
 */
@Slf4j
@Component
public class AccessTokenHolder {
    @Autowired
    private TokenUtil tokenUtil;

    // 检测token在redis中是否存在(jwt)
    // 1, 白名单机制, 存在则表示可用, 即处于登入状态(选择白名单,监测用户是否在线)
    // 2, 黑名单机制, 存在则表示不可用, 即处于登出状态
    @Async
    public Future<Boolean> checkAccountAccessToken(String path, UserDto userDto) {
        return new AsyncResult<>(tokenUtil.checkAccessToken(hashKey(userDto), userDto.getId()));
    }

    @Async
    public void invalidateToken(UserDto userDto){
        tokenUtil.removeAccessToken(hashKey(userDto));
    }

    private String hashKey(UserDto userDto){
        return userDto.getClientId() + "_" + userDto.getId();
    }
}
